//
//  VRSelectTagView.swift
//  VoiceRoom
//
//  Created by Rui on 2024/3/14.
//

import UIKit

class VRSelectTagView: UIView, SAAnimationDelegate, SAAnimationProtocol {

    func animationContainerViewSize() -> CGSize {
        CGSize(width: .screenWidth, height: 430)
    }
    
    func animationContainerViewStyle() -> SAAnimationViewStyle {
        .bottom
    }
    
    private lazy var titleLabel = c_make_ex(UILabel.self)
        .color(.white).font(18.font_bold).alignment(.center)
        .text("Select Tag").end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    
    var dataList:[VRTagItemModel] = {
       let arr = ["Esports","Cinephile","Fashion","Music","Gourmet","Technology","Fitness"
                  ,"Travel","Art","Style","Gaming","Movies","Novels","Sports","Cooking","Photography","Mobile Games"
                  ,"Celebrities","Jokes","Anime","Cosplay","Vlogging","Crafting","Literature","Adventure","Comedy",
                  "Celebs","Pets","DIY","History"]
        var data = [VRTagItemModel]()
        for str in arr {
            let model = VRTagItemModel(title: "#" + str, isSel: false)
            data.append(model)
        }
        return data
    }()
    
    var tagStringsBlock: ((_ tags: String) -> Void)?
    
    deinit {
        
        var tagsArray = [String]()
        for md in dataList {
            if md.isSel {
                tagsArray.append(md.title)
            }
        }
        
        let tagStrings = tagsArray.joined(separator: ",")
        tagStringsBlock?(tagStrings)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = "#1F1E18".toColor
        self.fj.corner(20, corners: [.layerMinXMinYCorner,.layerMaxXMinYCorner])
        
        subviews{
            titleLabel
            collectionView
        }
        
        titleLabel.top(20).centerHorizontally()
        collectionView.leading(0).trailing(0).top(60).bottom(0)
        
        let layout = UICollectionViewLeftAlignedLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        layout.sectionInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(VRTagCollectionItem.self, forCellWithReuseIdentifier: VRTagCollectionItem.description())
            v.showsVerticalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension VRSelectTagView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: VRTagCollectionItem.description(), for: indexPath) as? VRTagCollectionItem else { return UICollectionViewCell() }
        item.model = dataList[indexPath.row]
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        var selCount = 0
        for md in dataList {
            if md.isSel {
                selCount += 1
            }
        }
        
        var model = dataList[indexPath.row]
        if selCount >= 3 && !model.isSel{
            return
        }
        
        model.isSel = !model.isSel
        dataList[indexPath.row] = model
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let model = dataList[indexPath.row]
//        var w = model.title.caculateWidth(CGSize(width: 85, height: 30), 14.font_medium!)
        var w = (model.title as NSString).size(withAttributes: [NSAttributedString.Key.font: 14.font_medium!]).width
        w = w + 30.0
        return CGSize(width: w, height: 30)
    }
}

class VRTagCollectionItem: UICollectionViewCell {
    
    private let tagView = c_make_ex(UIButton.self)
        .corner(15).border(.white.alpha(0.6),width: 1)
        .font(14.font_medium).color(.white.alpha(0.6))
        .color("#FFFC00".toColor,state: .selected).end()
    
    var model: VRTagItemModel?{
        didSet{
            guard let md = model else { return }
            tagView.setTitle(md.title, for: .normal)
            tagView.isSelected = md.isSel
            if md.isSel {
                tagView.layer.borderColor = "#FFFC00".toColor.cgColor
            }else{
                tagView.layer.borderColor = UIColor.white.alpha(0.6).cgColor
            }
            tagView.layer.borderWidth = 1
            tagView.layer.masksToBounds = true
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.subviews {
            tagView
        }
        tagView.fillContainer()
//        tagView.contentEdgeInsets = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
        tagView.isUserInteractionEnabled = false
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
